I have an api that validates and creates user. When I don't type email in request's body I receive
{
"timestamp": "2020-11-26T13:55:40.116+00:00",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='user'. Error count: 1",
"path": "/api/users"
}
I want to change message to more understable error like "email must be not null". That's how my model's property looks:
@NotNull
private String email;
And here is my controller's method:
@PostMapping("/users")
public ResponseEntity<User> addUser(@RequestBody @Valid User user) {
User savedUser = manager.save(user);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.ok(savedUser);
}
I've tried to set custom message in @NotNull annotation, but the message doesn't change. Also when the error gets thrown console shows this message:
2020-11-26 15:09:11.460 WARN 7137 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<pl.vemu.socialApp.entities.User> pl.vemu.socialApp.controllers.UserController.addUser(pl.vemu.socialApp.entities.User) throws pl.vemu.socialApp.exceptions.user.UserWithEmailAlreadyExistException: [Field error in object 'user' on field 'email': rejected value [xsars.pl]; codes [Email.user.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@2a50b33,.*]; default message [must be a well-formed email address]] ]
How to set the message in response json?
How to get rid of this message in console? Other errors don't show message in console.
The problem is that Spring by default doesn't send errors while binding. To enable it you have to add server.error.include-binding-errors=always in your application.properties.
Instead of relying on "message" property, you can use "defaultMessage" property.
You can set a custom error message on @NotNull annotation.
@NotNull(message = "Name cannot be null")
private String name;
@NotNull(message = "email cannot be null")
@NotEmpty(message = "email cannot be empty")
private String email;
If validation fails for a field, spring will set these custom messages on "defaultMessage" property
As you said in the comments that you couldn't find defaultMessage, another approach (perhaps the dirty approach) would be to manually create the response body, you can refer the following sample code to build it:
@PostMapping("saveEmployee")
public ResponseEntity<?> eat(@RequestBody @Valid Employee employee, Errors errors) {
if (errors.hasFieldErrors()) {
FieldError fieldError = errors.getFieldError();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(fieldError.getDefaultMessage());
}
return ResponseEntity.ok(employee);
}
FieldError#getDefaultMessage() will expose the value of message attribute in @NotNull(message = "email can't be null")
ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("email must be not null");
and replace HttpStatus.UNPROCESSABLE_ENTITY with a suitable error code.